from common import handle_case
import time
import json
import threading
from common.handle_config import *
tokenId = ""
res_id = ""
special_data = {}
import re

class utrailer_case(handle_case.Handle_Data):
    def set_data(self):
        # 从excel中读取url，请求方法，请求参数，请求头
        if self.table.row_values(self.index)[2] == "":
            self.data = None
            return self.data
        else:
            self.data = json.loads(self.table.row_values(self.index)[2])
        # 税筹修改订单时间
        self.change_order_time()

        # 运营端详情id
        if "api/contract/detail" in self.url or "api/vmOrder/info" in self.url or "/api/linePublish/queryLineDetail" in self.url:
            self.admin_id_detail()
        # 货主端详情id
        if "web/order/info" in self.url or "web/vmOrder/info" in self.url or "resource/driver/detail" in self.url or \
                self.url.split("/")[-1] == "cancel" or (
                "vm/vehicle/apply/detail" in self.url and "admin" not in self.url) or "resource/vehicle/detail" in self.url or "resource/payeeinfo/detail" in self.url:
            self.ebs_id_detail()
        if "api/linePublish/queryApplyDetail" in self.url:
            self.admin_special_detail()
        return self.data


    def set_headers(self):
        self.headers = eval(self.table.row_values(self.index)[3])
        # 获取tokenId
        if "tokenId" in list(self.headers.keys()) or "tokenid" in list(self.headers.keys()):
            self.get_tokenId()
        return self.headers

    # 获取tokenId
    def get_tokenId(self):
        if "admin" not in self.url:
            self.headers["tokenId"] = tokenId
        if "admin" in self.url:
            self.headers["tokenid"] = tokenId

    def set_url(self):
        # url带id
        if "api/company/detail/" in self.url or "api/vehicle/getDetail/" in self.url or "api/payeeInfo/detail/" in self.url or "contract/zz/detail/" in self.url or "api/invoice/detail/" in self.url or "api/rebate/detail/" in self.url or "api/order/detail/" in self.url or "api/payment/nodes/" in self.url or "api/driver/getDetail/" in self.url or "api/vehicle/getVmVehicleDetail/" in self.url or (
                "vehicle/apply/detail/" in self.url and "admin" in self.url) or "api/vehicleApplyRecord/info/" in self.url or "/api/vm-pool/info/" in self.url or "work-order/detail/" in self.url or "/api/cargo/detail" in self.url:
            self.res_detail()
        return self.url

    def assert_result(self):
        res_json = self.res.json()
        if self.method.upper() == "POST":
            # 先断言url返回的结果，一般为200才继续后面流程
            assert (self.res.status_code == 200)
            # 税筹接口特殊判断
            self.interface_callback()
            # 判断返回值的长度
            try:
                if self.table.row_values(self.index)[4] == 1:
                    assert (len(res_json["body"]["data"]) > 0)
            except Exception:
                if self.table.row_values(self.index)[4] == 1:
                    assert (len(res_json["data"]["data"]) > 0)
            # 特征1必须有，判断特征1是否在返回的数据中
            if self.table.row_values(self.index)[5] != "":
                assert (self.table.row_values(self.index)[5] in json.dumps(res_json, ensure_ascii=False))
            # 压力测试
            if self.table.row_values(self.index)[6] != "":
                thread_pool = []
                for i in range(int(self.table.row_values(self.index)[6])):
                    thread = threading.Thread(target=self.get_response)
                    thread_pool.append(thread)
                for th in thread_pool:
                    th.start()
                for th in thread_pool:
                    threading.Thread.join(th)
            # 特征2，3可以有，判断特征2,3是否在返回的数据中
            if self.table.row_values(self.index)[7] != "":
                assert (self.table.row_values(self.index)[7] in json.dumps(res_json, ensure_ascii=False))
            else:
                assert True
            if self.table.row_values(self.index)[8] != "":
                assert (self.table.row_values(self.index)[8] in json.dumps(res_json, ensure_ascii=False))
            else:
                assert True
        # get请求只判断返回的code
        elif self.method.upper() == "GET":
            print(res_json)
            assert (self.res.status_code == 200)
        else:
            assert False

    # 接口判断
    def interface_callback(self):
        res_json = self.res.json()
        print(res_json)
        if "login" in self.url and "admin" not in self.url:
            global tokenId
            tokenId = res_json["body"]["sessionId"]
        if "login" in self.url and "admin" in self.url:
            tokenId = res_json["data"]["token"]
        if "api/company/list" in self.url or "api/vehicle/list" in self.url or "api/payeeInfo/list" in self.url or "api/contract/list" in self.url or "api/contract/zz/list" in self.url or "api/invoice/list" in self.url or "api/rebate/list" in self.url or "api/vmOrder/list" in self.url or "api/vehicle/vmList" in self.url or (
                "admin" in self.url and "vm/vehicle/apply/list" in self.url) or "api/vehicleApplyRecord/list" in self.url or "api/vm-pool/list" in self.url or "/api/work-order/list" in self.url or "/api/cargo/list" in self.url or (
                "/api/linePublish/queryLine" in self.url and "Detail" not in self.url):
            global res_id
            res_id = res_json["data"]["data"][0]["id"]
        if "web/order/list" in self.url or "web/vmOrder/list" in self.url or "resource/driver/list" in self.url or (
                "admin" not in self.url and "vm/vehicle/apply/list" in self.url) or "resource/payeeinfo/list" in self.url or "resource/vehicle/list" in self.url:
            res_id = res_json["body"]["data"][0]["id"]
        if "api/driver/list" in self.url:
            res_id = res_json["data"]["data"][0]["phone"]
        if "api/order/list" in self.url or "api/order/exception/list" in self.url:
            res_id = res_json["data"]["data"][0]["orderId"]
        if "api/payment/list" in self.url:
            res_id = res_json["data"]["data"][0]["priceItemId"]
        if "/api/linePublish/queryApply" in self.url and "Detail" not in self.url:
            global special_data
            special_data = {"id": res_json["data"]["data"][0]["id"],
                            "linePublishId": res_json["data"]["data"][0]["linePublishId"],
                            "linePublishInfoId": res_json["data"]["data"][0]["linePublishInfoId"]}

    # 税筹修改订单时间
    def change_order_time(self):
        if "body" in list(self.data.keys()):
            if "expArriveTime" in list(self.data["body"].keys()) and "expDepartTime" in list(self.data["body"].keys()):
                self.data["body"]["expDepartTime"] = time.strftime("%Y-%m-%d %H:%M:%S",
                                                                   time.localtime(time.time() + 60 * 60))
                self.data["body"]["expArriveTime"] = time.strftime("%Y-%m-%d %H:%M:%S",
                                                                   time.localtime(time.time() + 60 * 60 * 5))
            if "loadTime" in list(self.data["body"].keys()) and "loadFinishTime" in list(self.data["body"].keys()):
                self.data["body"]["loadTime"] = time.strftime("%Y-%m-%d %H:%M:%S",
                                                              time.localtime(time.time() + 60 * 60))
                self.data["body"]["loadFinishTime"] = time.strftime("%Y-%m-%d %H:%M:%S",
                                                                    time.localtime(time.time() + 60 * 60))
                self.data["body"]["unLoadTime"] = time.strftime("%Y-%m-%d %H:%M:%S",
                                                                time.localtime(time.time() + 60 * 60 * 5))
                self.data["body"]["unLoadFinishTime"] = time.strftime("%Y-%m-%d %H:%M:%S",
                                                                      time.localtime(time.time() + 60 * 60 * 5))

    # 运营端详情-url
    def res_detail(self):
        self.url = self.url.replace("123", str(res_id))

    # 运营详情
    def admin_id_detail(self):
        self.data["id"] = str(res_id)

    # 运营端报名记录特殊接口
    def admin_special_detail(self):
        self.data = special_data

    # 货主端详情
    def ebs_id_detail(self):
        self.data["body"]["id"] = str(res_id)
